package com.seu.algorithms.utils;

import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

/**
 * MD5通用类
 *
 * @version 1.0.0_1
 * @since 2013.01.15
 */
public class MD5 {
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static String MD5Encode(String origin) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } catch (Exception ex) {
        }
        return resultString;
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i], true));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b, boolean bigEnding) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return (bigEnding) ? (hexDigits[d1] + hexDigits[d2]) : (hexDigits[d2] + hexDigits[d1]);
    }

    /**
     * MD5方法
     *
     * @param text 明文
     * @param key  密钥
     * @return 密文
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    public static String md5(String text, String key) {
        return Hashing.md5().hashString(text + key, Charsets.UTF_8).toString();
    }


    /**
     * MD5验证方法
     *
     * @param text 明文
     * @param key  密钥
     * @param md5  密文
     * @return true/false
     * @throws Exception
     */
    public static boolean verify(String text, String key, String md5) {
        String md5Text = md5(text, key);
        if (md5Text.equals(md5)) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(md5("18824306500,15282375577,15584938012,18640969860,18124211456,15513361990,18676344174,18810277646,13594952750,18500937093,13454322993,13818126273,13370154288,15934349577,13860697180,13945757757,13598336190,15869399413,15262288776,15735353850,15735353850,18780473910,15652280093,15578888204,quantgroupgroupquant", "quantgroupgroupquant"));
            System.out.println(verify("18824306500,15282375577,15584938012,18640969860,18124211456,15513361990,18676344174,18810277646,13594952750,18500937093,13454322993,13818126273,13370154288,15934349577,13860697180,13945757757,13598336190,15869399413,15262288776,15735353850,15735353850,18780473910,15652280093,15578888204,", "quantgroupgroupquant", "6d42050818e83b474a11336204dd9048"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}